package fm.dongman.animefm.view.fragment

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Bitmap
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import fm.dongman.animefm.R
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.MyContract
import fm.dongman.animefm.view.activity.SettingActivity
import fm.dongman.animefm.view.activity.SingleActivity
import fm.dongman.animefm.view.transform.GlideRoundTransform
import fm.dongman.animefm.view.util.ActivityHelper
import fm.dongman.animefm.view.util.SystemHelper
import fm.dongman.animefm.view.util.ToastHelper
import fm.dongman.modellib.StaticArea.Injection
import fm.dongman.modellib.model.UserModel
import fm.dongman.presenterlib.presenter.MyPresenter
import kotlinx.android.synthetic.main.fragment_my.*
import org.jetbrains.anko.onClick
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult

/**
 * 我的页面
 * Created by shize on 2017/9/28.
 */
class MyFragment : BaseFragment(), MyContract.IMyView, View.OnClickListener {
    private lateinit var mPresenter: MyContract.IMyPresenter  // 全局数据控制器
    private var myBroadcast: MyBroadcast? = null
    private var userInfo1: IModel.IUserModel? = null
    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val fragment = inflater?.inflate(R.layout.fragment_my, container, false)
        MyPresenter(this, Injection.provideMyRepository(container!!.context))
        // 初始化控制器
        return fragment!!
    }

    override fun setPresenter(presenter: MyContract.IMyPresenter) {
        mPresenter = presenter

    }

    override fun initData() {
        if (userInfo1 != null) {
            showMyLogin(userInfo1!!)
        } else {
            showMyLogout() //初始化未登录个人信息页
        }
    }

    override fun bindData() {
        mTbMy.setPadding(0, SystemHelper.getStatusBarHeight(activity), 0, 0)
        registerReceiver() //注册广播
        bindBtnClick()       //个人信息页事件
        mPresenter.startLoad()
    }

    private fun registerReceiver() {
        val filter = IntentFilter(INTENT_LOGIN)
        myBroadcast = MyBroadcast()
        activity.registerReceiver(myBroadcast, filter)
    }

    //My页面所有事件
    private fun bindBtnClick() {
        mRlMyUserInfoUpdate.setOnClickListener(this)
        mRvMyFriendGroup.setOnClickListener(this)
        mRvMyComment.setOnClickListener(this)
        mRvMyAnimeWatched.setOnClickListener(this)
        mRvMySheetCreated.setOnClickListener(this)
        mRvMySheetCollection.setOnClickListener(this)
        mRvMyTopicCollection.setOnClickListener(this)
        //设置
        mSetting.onClick {
            activity.startActivity<SettingActivity>()
        }
        // 我的消息
        mLlMyMessage.onClick {
            val intent = Intent(activity, SingleActivity::class.java)
            intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_CHAT_LIST)
            ActivityHelper.startActivity(activity, intent)
        }
        // 我的关注
        mLlMyFocus.onClick {
            ActivityHelper.startActivity(activity, SingleActivity::class.java, mapOf(
                    Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_USER_LIST),
                    Pair(SingleActivity.BUNDLE_EXTRA_KEY_TYPE, UserListFragment.TYPE_FOLLOW)
            ), false)
        }
        // 我的粉丝
        mLlMyFans.onClick {
            ActivityHelper.startActivity(activity, SingleActivity::class.java, mapOf(
                    Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_USER_LIST),
                    Pair(SingleActivity.BUNDLE_EXTRA_KEY_TYPE, UserListFragment.TYPE_FAN)
            ), false)
        }
    }

    override fun onClick(v: View?) {
        if (!checkIsLogin()) {
            val intent = Intent(activity, SingleActivity::class.java)
            intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_LOGIN)
            ActivityHelper.startActivity(activity, intent)
            return
        }
        when (v!!.id) {

            R.id.mRlMyUserInfoUpdate -> {
                //修改个人信息
                val intent = Intent(activity, SingleActivity::class.java)
                intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_USER_INFO_UPDATE)
                // ActivityHelper.startActivity(activity as Activity, intent)
                startActivityForResult(intent, 1)
            }

            R.id.mRvMyFriendGroup -> {
                //敬请期待
                ToastHelper.getInstance(activity).showWarn("敬请期待！")
            }
            R.id.mRvMyComment -> {
                //我的评论
                ActivityHelper.startActivity(activity, SingleActivity::class.java,
                        mapOf(Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_COMMENT_LIST),
                                Pair(SingleActivity.BUNDLE_EXTRA_KEY_TYPE, CommentListFragment.TYPE_MINE)),
                        false)
            }

            R.id.mRvMyAnimeWatched -> {
                //看过的动漫
                ActivityHelper.startActivity(activity, SingleActivity::class.java,
                        mapOf(Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_COMIC_LIST),
                                Pair(SingleActivity.BUNDLE_EXTRA_KEY_TYPE, ComicListFragment.TYPE_LOOK)),
                        false)
            }
            R.id.mRvMySheetCreated -> {
                //创建的漫单
                ActivityHelper.startActivity(activity, SingleActivity::class.java,
                        mapOf(Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_SHEET_LIST),
                                Pair(SingleActivity.BUNDLE_EXTRA_KEY_TYPE, SheetListFragment.TYPE_USER_CREATE))
                        , false)
            }
            R.id.mRvMySheetCollection -> {
                //关注的漫单
                ActivityHelper.startActivity(activity, SingleActivity::class.java,
                        mapOf(Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_SHEET_LIST),
                                Pair(SingleActivity.BUNDLE_EXTRA_KEY_TYPE, SheetListFragment.TYPE_USER_FOLLOW))
                        , false)
            }
            R.id.mRvMyTopicCollection -> {
                //收藏的专题
                ActivityHelper.startActivity(activity, SingleActivity::class.java,
                        mapOf(Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_SHEET_LIST),
                                Pair(SingleActivity.BUNDLE_EXTRA_KEY_TYPE, SheetListFragment.TYPE_USER_COL))
                        , false)
            }
        }
    }

    /**
     * 是否登录
     */
    private fun checkIsLogin(): Boolean = userInfo1 != null

    override fun showRefreshFailed() {
        // ToastHelper.getInstance(activity).showError("my 页面" + getString(R.string.str_refresh_failed))
    }

    override fun isActive(): Boolean = isAdded

    override fun getViewContext(): Context = activity

    override fun showNoNetwork() {
        //ToastHelper.getInstance(activity).showError("没有网络！")
    }

    override fun showMyLogout() {
        mTvMyNickname.text = "请先登录"
        Glide.with(activity).load(R.mipmap.avatar).bitmapTransform(CenterCrop(activity), GlideRoundTransform(activity, 24)).into(mIvMyAvatar)
        mTvMyDescription.text = "登录获得更优质的体验"
        mUserFansNum.text = "0"
        message.text = "0"
        mTvMyfollow.text = "0"
        MyContract.USER_ID = null
    }

    override fun showMyLogin(userInfo: IModel.IUserModel) {
        val user = (userInfo as UserModel)
        Glide.with(activity).load(user.avatarUrl).bitmapTransform(CenterCrop(activity), GlideRoundTransform(activity, 24)).into(mIvMyAvatar)
        mTvMyNickname.text = user.userName
        mTvMyDescription.text = user.description
        mUserFansNum.text = user.fansNum
        message.text = user.messageNum
        mTvMyfollow.text = user.flowNum
        MyContract.USER_ID = user.userId
        userInfo1 = userInfo
    }

    override fun onDestroyView() {
        super.onDestroyView()
        activity.unregisterReceiver(myBroadcast)
    }

    /**
     * 广播接收器
     */
    inner class MyBroadcast : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            userInfo1 = intent!!.getParcelableExtra(KEY_USER_INFO)
            val strAction = intent.getStringExtra(INTENT_LOGIN_FLOG)
            if (strAction == INTENT_LOGIN_OUT) { //退出账号清除数据
                showMyLogout()
                return
            }
            myInfo()    //my界面初始化赋值
        }
    }

    fun myInfo() {
        mTvMyNickname.text = (userInfo1 as UserModel).userName
        Glide.with(activity).load((userInfo1 as UserModel).avatarUrl)
                .bitmapTransform(CenterCrop(activity), GlideRoundTransform(activity, 24)).into(mIvMyAvatar)
        showMyLogin(userInfo1 as UserModel) //调用回调方法赋值数据
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK) {
            mPresenter.refreshPage() //刷新页面数据
        } else {
            ToastHelper.getInstance(activity).showSucceed("返回失败")
        }
    }

    companion object {
        private var FRAGMENT_INSTANCE: MyFragment? = null
        val INTENT_LOGIN = "fm.dongman.animenfm.intent.login"
        val KEY_USER_INFO = "userInfo"
        val INTENT_LOGIN_FLOG = "flog"
        val INTENT_LOGIN_OUT = "out"
        /**
         * 获取实例
         */

        fun getInstance(): MyFragment {
            if (FRAGMENT_INSTANCE == null) {
                FRAGMENT_INSTANCE = MyFragment()
            }
            return FRAGMENT_INSTANCE!!
        }

        /**
         * 销毁实例
         */
        fun destroyInstance() {
            FRAGMENT_INSTANCE = null
        }
    }
}